﻿using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using CeskyRozhlasWP8.Model;
using CeskyRozhlasWP8.ViewModel;
using Microsoft.Phone.Controls;
using WP8DataModel.Model;
using WP8DataModel.ViewModel;

namespace CeskyRozhlasWP8.View
{
    sealed public partial class FullShowDescriptionPage : PhoneApplicationPage
    {
        private DispatcherTimer _progressBarRefreshTimer;

        private void StartProgressbarRefreshTimer()
        {
            _progressBarRefreshTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
            _progressBarRefreshTimer.Tick += progressBarRefreshTimer_Tick;
            _progressBarRefreshTimer.Start();
        }
        private void progressBarRefreshTimer_Tick(object sender, EventArgs e)
        {
            UpdateProgressBar();
        }


        private void UpdateProgressBar()
        {
            if (_viewModel.CurrentShow != null)
            {
                var aLocalStartTime = _viewModel.CurrentShow.StartTime.ToLocalTime();
                var aLocalStopTime = _viewModel.CurrentShow.StopTime.ToLocalTime();
                MyProgressBar.Minimum = 0;
                var aDuration = aLocalStopTime.Subtract(aLocalStartTime);
                var aCurrentStatus = DateTime.Now.Subtract(aLocalStartTime);
                MyProgressBar.Maximum = aDuration.TotalMilliseconds;
                MyProgressBar.Value = aCurrentStatus.TotalMilliseconds;
                MyProgressBar.Visibility = Visibility.Visible;
            }
        }

        
        private readonly FullShowDescriptionViewModel _viewModel = new FullShowDescriptionViewModel();

        public FullShowDescriptionPage()
        {
            InitializeComponent();
            DataContext = _viewModel;
        }

        private long _showId;

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            BackgroundScheduleModel.Instance.SubmitChanges();
            StopProgressBarRefreshTimer();
            base.OnNavigatedFrom(e);
        }

        private void StopProgressBarRefreshTimer()
        {
            if (_progressBarRefreshTimer != null)
            {
                //TODO: where is Dispose method for this timer? Should I manually do "-="?
                _progressBarRefreshTimer.Tick -= progressBarRefreshTimer_Tick;
                _progressBarRefreshTimer.Stop();
                _progressBarRefreshTimer = null;
            }
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var aShowIdParam = NavigationContext.QueryString["showId"];
            await RefreshPage(aShowIdParam);
            StartProgressbarRefreshTimer();
            UpdateProgressBar();
            base.OnNavigatedTo(e);
        }

        private async Task RefreshPage(string aShowIdParam)
        {
            _showId = 0;
            Int64.TryParse(aShowIdParam, out _showId);
            //TODO: work on null refs
            _viewModel.CurrentShow = await ShowsData.Instance.GetShowById(_showId);
            if (_viewModel.CurrentShow != null)
            {
                
            _viewModel.Station =
                await ShowsData.Instance.GetStationById(_viewModel.CurrentShow.StationId);
            _viewModel.CurrentBackgroundScheduledTransfer = FetchOrCreateScheduleItem(_viewModel.CurrentShow);
                ShowReminderCheckBox.IsEnabled = _viewModel.CurrentShow.StartTime > DateTime.Now;
            }
        }



        private BackgroundScheduledTransferItem FetchOrCreateScheduleItem(DetailedScheduleItem iShow)
        {
            var aItem = BackgroundScheduleModel.Instance.Fetch(iShow.Id);
            if (aItem == null)
            {
                aItem = iShow.ToBackgroundScheduledTransferItem(_viewModel.Station.ShortName);
                BackgroundScheduleModel.Instance.Append(aItem);
            }
            return aItem;
        }

        private void ShowReminderCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            PlaybackRemindersManager.AddReminder(_viewModel.CurrentShow);
            //TODO: validate this setting if it conflicts with any other
        }

        private void ShowReminderCheckBox_OnUnchecked(object sender, RoutedEventArgs e)
        {
            PlaybackRemindersManager.RemoveReminder(_viewModel.CurrentShow);
        }
    }
}